<template>
  <div class="component-upload-image">
    <el-upload
      :action="uploadImgUrl"
      list-type="picture-card"
      :on-success="handleUploadSuccess"
      :before-upload="handleBeforeUpload"
      :on-error="handleUploadError"
      name="file"
      :show-file-list="false"
      :headers="headers"
      style="display: inline-block; vertical-align: top"
    >
      <el-image v-if="!value" :src="value">
        <template #error>
          <div class="image-slot">
            <i class="el-icon-plus" />
          </div>
        </template>
      </el-image>
      <div v-else class="image">
        <el-image :src="value" :style="`width:150px;height:150px;`" fit="fill"/>
        <div class="mask">
          <div class="actions">
            <span title="预览" @click.stop="dialogVisible = true">
              <i class="el-icon-zoom-in" />
            </span>
            <span title="移除" @click.stop="removeImage">
              <i class="el-icon-delete" />
            </span>
          </div>
        </div>
      </div>
    </el-upload>
    <el-dialog v-model="dialogVisible" title="预览" width="800" append-to-body>
      <img :src="value" style="display: block; max-width: 100%; margin: 0 auto;">
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import { getToken } from '@/utils/auth'
import config from '@/config'

interface HeadersType {
  Authorization: string;
}
interface DataType {
  dialogVisible: boolean;
  uploadImgUrl: string | undefined;
  headers: HeadersType;
}
export default defineComponent({
  name: 'ImageUpload',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  setup(_, context) {
    const data = reactive<DataType>({
      dialogVisible: false,
      uploadImgUrl: config.baseURL + '/common/upload',
      headers: {
        Authorization: 'Bearer ' + getToken()
      }
    })
    const removeImage = () => {
      context.emit('input', '')
    }
    const handleUploadSuccess = (res: any) => {
      context.emit('input', res.url)
    }
    const handleBeforeUpload = () => {
      // 加载中
    }
    const handleUploadError = () => {
      ElMessage({
        message: '上传失败',
        type: 'error'
      })
    }
    return {
      handleUploadError,
      handleBeforeUpload,
      removeImage,
      handleUploadSuccess,
      ...toRefs(data)
    }
  }
})
</script>

<style scoped lang="scss">
.image {
  position: relative;
  .mask {
    opacity: 0;
    position: absolute;
    top: 0;
    width: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    transition: all 0.3s;
  }
  &:hover .mask {
    opacity: 1;
  }
}
</style>